package com.rdxer.api;

import com.rdxer.dataview.UserInfoSelfDV;
import com.rdxer.model.Account;
import com.rdxer.core.security.AppUserDetails;
import com.rdxer.core.entity.Result;
import com.rdxer.core.exception.exceptions.BaseException;
import com.rdxer.service.AccountService;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
public class AccountApi {

    @Resource
    AccountService accountService;
    @Autowired
    PasswordEncoder passwordEncoder;


    @RequestMapping("/userinfo")
    Result<UserInfoSelfDV> getCurrentUserinfo(@AuthenticationPrincipal Principal principal) {
        Account acc = accountService.findByName(principal.getName());

        UserInfoSelfDV userinfo = new UserInfoSelfDV();

        BeanUtils.copyProperties(acc, userinfo);

        String[] split = acc.getRoles().split(",");
        userinfo.setRoles(split);

        Result<UserInfoSelfDV> result = Result.ofSucceed(userinfo);

        return result;
    }


    @PutMapping("/userInfo")
    public Result<Account> update(@AuthenticationPrincipal AppUserDetails appUserDetails, @RequestBody UpdateAccountPara para) {

        Account currentAccount = appUserDetails.getAccount();

        if (!currentAccount.getId().equals(para.getId())) {
            throw BaseException.ofForbidden("没有权限");
        }

        Account a = new Account();

        if (!StringUtils.isEmpty(para.getPassword())) {
            para.setPassword(passwordEncoder.encode(para.getPassword()));
        }

        BeanUtils.copyProperties(para, a);

        Account account1 = accountService.updateOfPatch(para.getId(), a);

        return Result.ofSucceed(account1);
    }

    @DeleteMapping("/userInfo/destroy")
    public Result destroy(@AuthenticationPrincipal Principal principal, @PathVariable Long id) {

        Account currentAccount = accountService.findByName(principal.getName());

        if (!currentAccount.getId().equals(id)) {
            throw BaseException.ofForbidden("没有权限");
        }

        currentAccount.setDisabledDate(System.currentTimeMillis());
        accountService.update(currentAccount);

        return Result.ofSucceed("禁用成功");
    }

    @Data
    public static class UpdateAccountPara {

        private String id;

        private String avatar;
        private String displayName;
        private String email;
        private String phone;

        private String password;

    }

}
